﻿using CleanArchitecture.Core.Interfaces.Cache;
using CleanArchitecture.Infrastructure.Configuration;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Entities.Business;
using CleanArchitecture.Infrastructure.Interfaces;
using CleanArchitecture.Infrastructure.Interfaces.Business;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace CleanArchitecture.Infrastructure.Services.Business
{
    public partial class LanguageService : ILanguageService
    {
        #region Fields
        private readonly IRepository<Language> _langRepository;
        private readonly IStaticCacheManager _cacheManager;
        #endregion

        #region Ctor
        public LanguageService(IRepository<Language> langRepo,
            IStaticCacheManager cacheManager)
        {
            this._langRepository = langRepo;
            this._cacheManager = cacheManager;
        }

        public IList<Language> GetLanguagesAll()
        {
            string cacheKey = DefaultCacheConfig.LanguageCacheKey;
            return _cacheManager.Get(cacheKey, () =>
            {
                var query = _langRepository.Table;
                query = query.Where(l => l.IsActive == EntityEnumConfig.YesorNo.YES);
                query = query.OrderBy(l => l.DisplayOrder);
                return query.ToList();
            });
        }

        /// <summary>
        /// Get 2 letter ISO language code
        /// </summary>
        /// <param name="language">Language</param>
        /// <returns>ISO language code</returns>
        public virtual string GetTwoLetterIsoLanguageName(Language language)
        {
            if (language == null)
                throw new ArgumentNullException(nameof(language));

            if (string.IsNullOrEmpty(language.Culture))
                return "en";

            var culture = new CultureInfo(language.Culture);
            var code = culture.TwoLetterISOLanguageName;

            return string.IsNullOrEmpty(code) ? "en" : code;
        }
        #endregion
    }
}
